import sys
import os

from config.ServerApp import server_port
from config.LoggingConfig import *
from config.JobConfig import *
from config.InitMilvus import check_and_init_milvus
from controller.ImagClassifyController import *
import psutil


def kill_exist_process():
    # 获取当前正在运行的进程列表
    process_list = psutil.process_iter()
    for process in process_list:
        try:
            # 获取进程的所有打开的网络连接（使用新API）
            connections = process.net_connections()
            for conn in connections:
                # 检查是否有连接使用了指定的端口
                if conn.laddr.port == server_port:
                    # 结束进程
                    process.kill()
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess) as e:
            print("程序启动错误，杀死原有端口进程失败！{}！".format(e))
    pass


def get_config_path():
    if getattr(sys, 'frozen', False):
        # 如果程序被打包成了单文件
        application_path = os.path.dirname(sys.executable)
    else:
        # 如果程序是从源代码直接运行
        application_path = os.path.dirname(__file__)
    config_path = os.path.join(application_path, 'models')
    return config_path


if __name__ == "__main__":
    try:
        #1 杀死老进程
        kill_exist_process()

        # TODO 后续提前加载yolov10模型，使用单例加载
        # 设置模型文件路径
        s = get_config_path()
        os.environ['DEEPFACE_HOME'] = s
        os.environ['MODELSCOPE_CACHE'] = s
        print(f"DEEPFACE_HOME={s}")
        #2 初始化数据库
        # if not db_inited():
        #     init_db()
        # sqlite_db_upgrade()
        # reset_task_record_status()
        
        #3 初始化Milvus数据库
        try:
            check_and_init_milvus()
        except Exception as e:
            print(f"Milvus initialization failed: {e}")
        
        # 首次/空表自动导入类目（categories.json），幂等
        try:
            from config.InitDatabase import seed_categories_if_needed
            seed_categories_if_needed()
        except Exception as e:
            print(f"auto seed categories failed: {e}")
        get_clip_model(CLIP_MODEL_PATH)
        app.run(port=server_port,host="0.0.0.0", debug=True,workers=1,single_process=True)
    except Exception as e:
        print(e)
        pass
